package com.tingyuge.base.jdk.io.aio;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

/**
 * @Created by xiaodao
 */
public class AioClientReadHandler implements CompletionHandler<Integer, ByteBuffer> {
    private AsynchronousSocketChannel clientChannel;
    private CountDownLatch latch;
    public AioClientReadHandler(AsynchronousSocketChannel clientChannel, CountDownLatch latch) {
        this.clientChannel = clientChannel;
        this.latch=latch;

    }

    /**
     * 接受服务端的数据
     * @param result
     * @param byteBuffer
     */
    @Override
    public void completed(Integer result, ByteBuffer byteBuffer) {
        byteBuffer.flip();
        byte[] bytes = new byte[byteBuffer.remaining()];
        byteBuffer.get(bytes);
        try {
            String body = new String(bytes,"utf-8");
            System.out.println("accept: "+ body);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        System.err.println("读处理器->数据失败");
        try {
            clientChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        latch.countDown();
    }
}
